<?php

namespace liketp\view\php_native;

class FunctionProvider
{
    protected $dir;
    protected $data;
    protected $layout = '';
    protected $sections = [];
    protected $sectionStack = [];

    public function _render($tpl, $data): string
    {
        $this->dir = dirname($tpl);
        $this->data = $data;
        extract($data);
        ob_start();
        include $tpl;
        $content = ob_get_clean();

        while ($this->layout) {
            $layout = $this->layout;
            $this->layout = '';
            extract($this->data);
            ob_start();
            $this->sections['content'] = $content;
            include $layout;
            $content = ob_get_clean();
        }

        return $content;
    }

    public function echo($key)
    {
        echo to_str($this->data[$key] ?? '');
    }

    public function escape($key)
    {
        $val = to_str($this->data[$key] ?? '');
        echo htmlentities($val);
    }

    public function insert($file)
    {
        $file = $this->_getAndCheckFile($file, 'insert file not found');
        $file && require($file);
    }

    public function layout($file, $data = [])
    {
        $file = $this->_getAndCheckFile($file, 'layout file not found');
        $file && $this->layout = $file;
        $this->data = array_merge($this->data, $data);
    }

    public function section($sectionName)
    {
        return $this->sections[$sectionName] ?? '';
    }

    public function start($sectionName)
    {
        array_push($this->sectionStack, $sectionName);
        ob_start();
    }

    public function end()
    {
        $content = ob_get_contents();
        ob_end_clean();
        $secName = array_pop($this->sectionStack);
        $this->sections[$secName] = $content;
    }


    //------------------------------------------------ protected

    protected function _getAndCheckFile($file, $msg = '')
    {
        $filePath = $this->dir . DS . $file;
        if (file_exists($filePath)) {
            return $filePath;
        } else {
            if ($msg) {
                echo '<!--' . $msg . '-->';
            } else {
                return false;
            }
        }
    }
}
